/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package telsoft.cms_admin.utility;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import telsoft.cms_admin.data.DATA_FormTreeContents;
import telsoft.cms_admin.entity.ETT_Contents;
import telsoft.cms_admin.entity.ETT_TreeProduct;
import telsoft.cms_admin.util.BaseController;
import telsoft.util.StringUtil;

/**
 *
 * @author hoannc
 */
@ManagedBean(name = "treeContents")
@ViewScoped
public class FUNC_FormTreeContents extends BaseController implements Serializable {

    private boolean checkClearField = true;
    private ETT_Contents selectedRow;
    private ETT_Contents ETT_Contents;
    private ETT_Contents ETT_Contents_old;
    private List<ETT_Contents> listData = new ArrayList<ETT_Contents>();
    private ETT_TreeProduct ETT_Tree;
    private List<ETT_TreeProduct> listUser2Group = new ArrayList<ETT_TreeProduct>();
    private TreeNode root;
    private TreeNode selectedNodes;
    private boolean blSelected = false;
    private DATA_FormTreeContents Model = new DATA_FormTreeContents();

    
    
    public FUNC_FormTreeContents() {
//        super();
        try {
            init();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }

    }

    public boolean isCheckClearField() {
        return checkClearField;
    }

    public void setCheckClearField(boolean checkClearField) {
        this.checkClearField = checkClearField;
    }

    private void init() throws Exception {
        try {
//            listUser2Group = DataUtil.getData(DATA_FormTreeContents.class, "getUser2Group");
            listUser2Group = Model.getUser2Group();
            ETT_TreeProduct rootTN = new ETT_TreeProduct("Root", "0");
            root = new DefaultTreeNode(rootTN, null);
            // tree 
            buildTree(root);
            root.setExpanded(false);
            ETT_Contents = new ETT_Contents();
            bDisableModifyRemove = false;
            bFieldEnable = true;
            bDisableAddSearch = true;
            blSelected = false;
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void onNodeSelect(NodeSelectEvent event) {
        if (event == root) {
            bDisableModifyRemove = false;
            bFieldEnable = true;
            bDisableAddSearch = true;
            blSelected = false;
            ETT_Contents = new ETT_Contents();
            listData = new ArrayList<ETT_Contents>();
            selectedRow = new ETT_Contents();
        } else {
            try {

                ETT_Tree = (ETT_TreeProduct) event.getTreeNode().getData();
                if (ETT_Tree.getTYPE().equals("2")) {
//                    listData = (List<ETT_Contents>) DataUtil.performAction(DATA_FormTreeContents.class,
//                            "loadDetailProduct", ETT_Tree);
                    listData = Model.loadDetailProduct(ETT_Tree);
                    if (listData.isEmpty()) {
                        bDisableModifyRemove = false;
                        bFieldEnable = true;
                        bDisableAddSearch = false;
                        blSelected = false;
                        listData = new ArrayList<ETT_Contents>();
                        ETT_Contents = new ETT_Contents();
                        selectedRow = new ETT_Contents();
                    } else {
                        bDisableModifyRemove = true;
                        bFieldEnable = true;
                        bDisableAddSearch = false;
                        blSelected = true;
                        selectedRow = listData.get(0);
                        ETT_Contents = selectedRow;
                    }
                } else {
                    bDisableModifyRemove = false;
                    bFieldEnable = true;
                    bDisableAddSearch = true;
                    blSelected = false;
                    ETT_Contents = new ETT_Contents();
                    listData = new ArrayList<ETT_Contents>();
                }
            } catch (Exception ex) {
                addErrorMessage(ex);
                ex.printStackTrace();
            }
        }
    }

    private void buildTree(TreeNode parent) {
        ETT_TreeProduct treeValue = (ETT_TreeProduct) parent.getData();
        // Add child - group
        for (int i = 0; i < listUser2Group.size(); i++) {
            if (listUser2Group.get(i).getTYPE().equals("0")
                    && listUser2Group.get(i).getPARENT_ID().equals(treeValue.getID())) {
                ETT_TreeProduct rootTN = listUser2Group.get(i);
                TreeNode tmpTN = new DefaultTreeNode(rootTN, parent);
                tmpTN.setExpanded(true);
                buildTree(tmpTN);
            }
        }
        ///////////////////////
        for (int i = 0; i < listUser2Group.size(); i++) {
            if (listUser2Group.get(i).getTYPE().equals("1")
                    && listUser2Group.get(i).getPARENT_ID().equals(treeValue.getID())) {
                ETT_TreeProduct rootTN = listUser2Group.get(i);
                TreeNode tmpTN = new DefaultTreeNode(rootTN, parent);
                tmpTN.setExpanded(true);
                buildTree(tmpTN);
            }
        }
        // Add child - user
        for (int i = 0; i < listUser2Group.size(); i++) {
            if (listUser2Group.get(i).getTYPE().equals("2")
                    && listUser2Group.get(i).getPARENT_ID().equals(treeValue.getID())) {
                new DefaultTreeNode(listUser2Group.get(i), parent);
            }
        }
    }

    public void changeState(int iAction, boolean bNormalState) {
        if (bNormalState) {
            bRendered = false;
            bCancel = true;
            bSave = true;
        } else {
            bRendered = true;
            bCancel = false;
            bSave = false;
        }
        onChangeAction(iAction);
        setFieldEnable(bNormalState);
//        System.out.println(iAction);
    }

    private void add() {
        try {
            if (validateInput()) {
//                ETT_Contents ETT_ContentData = new ETT_Contents();
                ETT_Contents.setPRODUCT_ID(ETT_Tree.getID());
//                ETT_ContentData = (ETT_Contents) DataUtil.performAction(DATA_FormTreeContents.class, "insert", ETT_Contents);
                ETT_Contents = Model.insert(ETT_Contents);
                listData.add(ETT_Contents);

                //set selected row
                selectedRow = ETT_Contents;
                bDisableModifyRemove = true;
                blSelected = false;
            } else {
                fillDetailValue();
            }
        } catch (Exception ex) {
            addErrorMessage(ex);
            fillDetailValue();
            ex.printStackTrace();
        }
    }

    private void remove() {
        try {
//            DataUtil.performAction(DATA_FormTreeContents.class, "delete", selectedRow);
            Model.delete(selectedRow);
            //Update user interface
            listData.remove(selectedRow);

            //set selected row
            if (listData.isEmpty()) {
                bDisableModifyRemove = false;
            } else {
                selectedRow = listData.get(0);
                ETT_Contents = selectedRow;
            }
        } catch (Exception ex) {
            addErrorMessage(ex);
            fillDetailValue();
            ex.printStackTrace();
        }
    }

//    private void search() {
//        try {
//            listData = (List<ETT_Contents>) DataUtil.performAction(DATA_FormTreeContents.class, "search", ETT_Contents, ETT_Contents);
//            //Update UI
//            if (listData.isEmpty()) {
//                bDisableModifyRemove = false;
//                bFieldEnable = true;
//                bDisableAddSearch = true;
//                blSelected = false;
//                listData = new ArrayList<ETT_Contents>();
//                selectedRow = new ETT_Contents();
//            } else {
//                bDisableModifyRemove = true;
//                bFieldEnable = true;
//                bDisableAddSearch = false;
//                blSelected = true;
//                selectedRow = listData.get(0);
//                ETT_Contents = selectedRow;
//            }
//        } catch (Exception ex) {
//            addErrorMessage(ex);
//            fillDetailValue();
//            ex.printStackTrace();
//        }
//    }
    private void modify() {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        try {
            if (validateInput()) {
//                DataUtil.performAction(DATA_FormTreeContents.class, "update", selectedRow);
                Model.update(ETT_Contents);
                ETT_Contents.setStrCREATED_TIME(df.format(ETT_Contents.getCREATED_TIME()));
                ETT_Contents.setStrEFFECTIVE_TIME(df.format(ETT_Contents.getEFFECTIVE_TIME()));
                ETT_Contents.setStrEXPIRY_TIME(df.format(ETT_Contents.getEXPIRY_TIME()));
                //Update user interface
                int i = 0;
                for (ETT_Contents item : listData) {
                    if (item.getCONTENT_ID().equals(ETT_Contents.getCONTENT_ID())) {
                        listData.set(i, ETT_Contents);
                        selectedRow = ETT_Contents;
                        break;
                    }
                    i++;
                }
            } else {
                fillDetailValue();
            }
        } catch (Exception ex) {
            addErrorMessage(ex);
            fillDetailValue();
            ex.printStackTrace();
        }
    }

    public void onRowSelect() {
        try {
            bDisableModifyRemove = true;
            ETT_Contents = (ETT_Contents) selectedRow.clone();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void onChangeAction(int iOld_Action) {
        if (iOld_Action == ACTION_ADD || iOld_Action == ACTION_SEARCH
                || iOld_Action == ACTION_REMOVE || iOld_Action == ACTION_MODIFY || iOld_Action == ACTION_ADDCOPY) {
            if (iOld_Action == ACTION_ADD) {
                iAction = ACTION_ADD;
                if(checkClearField)clearFieldValue();
            } else if (iOld_Action == ACTION_MODIFY) {
                iAction = ACTION_MODIFY;
                clearFieldValue();
                fillDetailValue();
            } else if (iOld_Action == ACTION_ADDCOPY) {
                iAction = ACTION_ADDCOPY;
                clearFieldValue();
                fillDetailValue();
            } else if (iOld_Action == ACTION_SEARCH) {
                iAction = ACTION_SEARCH;
                clearFieldValue();
            } else if (iOld_Action == ACTION_REMOVE) {
                iAction = ACTION_REMOVE;
                clearFieldValue();
                doAction();
            }
        } else if (iOld_Action == ACTION_SAVE || iOld_Action == ACTION_CANCEL) {
            if (iOld_Action == ACTION_SAVE) {
                doAction();
            } else if (iOld_Action == ACTION_CANCEL) {
                fillDetailValue();
            }
        }
    }

    public void fillDetailValue() {
        try {
            ETT_Contents = (ETT_Contents) ETT_Contents_old.clone();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void clearFieldValue() {
        try {
            ETT_Contents_old = (ETT_Contents) ETT_Contents.clone();
            ETT_Contents = new ETT_Contents();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void doAction() {
        switch (iAction) {
            case ACTION_ADD:
                add();
                break;
            case ACTION_ADDCOPY:
                add();
                break;
            case ACTION_MODIFY:
                modify();
                break;
            case ACTION_SEARCH:
//                search();
                break;
            case ACTION_REMOVE:
                remove();
                break;
        }
    }

    public boolean validateInput() {
        if (StringUtil.nvl(ETT_Contents.getCONTENT_NAME(), "").equals("")) {
            addErrorMessage("Trường 'Tên nội dung' không được để trống!");
            checkClearField = false;
            return false;
        }
        if (ETT_Contents.getCREATED_TIME() == null) {
            addErrorMessage("Trường 'Ngày khởi tạo' không được để trống!");
            checkClearField = false;
            return false;
        }
        if (StringUtil.nvl(ETT_Contents.getSTATUS(), "").equals("")) {
            addErrorMessage("Trường 'Trạng thái' phải được chọn!");
            checkClearField = false;
            return false;
        }
        checkClearField = true;
        return true;
    }

    public void setFieldEnable(boolean b) {
        if (b) {
            bFieldEnable = false;
        } else {
            bFieldEnable = true;
        }
    }

    public ETT_Contents getSelectedRow() {
        return selectedRow;
    }

    public List<ETT_Contents> getListData() {
        return listData;
    }

    public void setSelectedRow(ETT_Contents selectedRow) {
        this.selectedRow = selectedRow;
    }

    public void setListData(List<ETT_Contents> listData) {
        this.listData = listData;
    }

    public ETT_Contents getETT_Contents() {
        return ETT_Contents;
    }

    public void setETT_Contents(ETT_Contents ETT_Contents) {
        this.ETT_Contents = ETT_Contents;
    }

    public ETT_Contents getETT_Contents_old() {
        return ETT_Contents_old;
    }

    public ETT_TreeProduct getETT_Tree() {
        return ETT_Tree;
    }

    public List<ETT_TreeProduct> getListUser2Group() {
        return listUser2Group;
    }

    public TreeNode getRoot() {
        return root;
    }

    public TreeNode getSelectedNodes() {
        return selectedNodes;
    }

    public void setETT_Contents_old(ETT_Contents ETT_Contents_old) {
        this.ETT_Contents_old = ETT_Contents_old;
    }

    public void setETT_Tree(ETT_TreeProduct ETT_Tree) {
        this.ETT_Tree = ETT_Tree;
    }

    public void setListUser2Group(List<ETT_TreeProduct> listUser2Group) {
        this.listUser2Group = listUser2Group;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    public void setSelectedNodes(TreeNode selectedNodes) {
        this.selectedNodes = selectedNodes;
    }

    public boolean isBlSelected() {
        return blSelected;
    }

    public void setBlSelected(boolean blSelected) {
        this.blSelected = blSelected;
    }
}
